<script setup lang="ts">
import { computed, ref, watch } from 'vue';

// 定义水果对象的类型
interface Fruit {
  id: number
  icon: string
  isChecked: boolean
  num: number
  price: number
}

// 默认数据数组
const defaultData = [
  {
    id: 1,
    icon: 'https://hongm-1312445828.cos.ap-nanjing.myqcloud.com/ll.png',
    isChecked: false,
    num: 2,
    price: 6,
  },
  {
    id: 2,
    icon: 'https://hongm-1312445828.cos.ap-nanjing.myqcloud.com/smt.png',
    isChecked: false,
    num: 7,
    price: 20,
  },
  {
    id: 3,
    icon: 'https://hongm-1312445828.cos.ap-nanjing.myqcloud.com/tg.png',
    isChecked: false,
    num: 3,
    price: 40,
  },
  {
    id: 4,
    icon: 'https://hongm-1312445828.cos.ap-nanjing.myqcloud.com/xg.png',
    isChecked: false,
    num: 10,
    price: 3,
  },
  {
    id: 5,
    icon: 'https://hongm-1312445828.cos.ap-nanjing.myqcloud.com/yl.png',
    isChecked: false,
    num: 20,
    price: 34,
  },
]
let fruitList = ref<Fruit[]>(defaultData)

// 水果列表
// 1. 从本地取数据
const localDataStr = localStorage.getItem('cart-data')
if (localDataStr && localDataStr !== '[]') {
  fruitList.value = JSON.parse(localDataStr) as Fruit[]
}

// 1. 删除
const delGoods = (id: number) => {
  fruitList.value = fruitList.value.filter(item => item.id !== id)
}

// 2. 减
const subGoods = (id: number) => {
  const item = fruitList.value.find(item => item.id === id)
  item && item.num--
}

// 3. 加
const addGoods = (id: number) => {
  const item = fruitList.value.find(item => item.id === id)
  item && item.num++
}

// 4. 全选和取消全选
// 正常写法
// const isAll = computed(() => {
//   return fruitList.value.every(item => item.isChecked)
// })

// 完整写法
const isAll = computed({
  get() {
    return fruitList.value.every(item => item.isChecked)
  },
  set(value) {
    // console.log(value);
    // 遍历修改数组中每一个对象的属性isChecked
    fruitList.value.forEach(item => item.isChecked = value)
  }
})

// 5. 选中商品的总数量
const total = computed(() => {
  return fruitList.value.reduce((sum, item) => {
    if (item.isChecked) {
      return sum + item.num
    } else {
      return sum
    }
  }, 0)
})

// 6. 选中商品的总价格
const totalPrice = computed(() => {
  return fruitList.value.reduce((sum, item) => {
    if (item.isChecked) {
      return sum + item.num * item.price
    } else {
      return sum
    }
  }, 0)
})

// 7. 数据持久化
watch(() => fruitList, (newData) => {
  console.log(newData.value);
  localStorage.setItem('cart-data', JSON.stringify(newData.value))
}, {
  // 深度侦听
  deep: true,
  // 一进入执行一次
  immediate: true
})

// --------------------------------
const person = { name: '张三', age: 18, gender: '男' }
const setData = () => {
  localStorage.setItem('person', JSON.stringify(person))
  localStorage.setItem('key', '2121212121')
}
const getData = () => {
  const str = localStorage.getItem('person')
  console.log(JSON.parse(str!));
}
const delData = () => {
  localStorage.removeItem('key')
}
const clearData = () => {
  localStorage.clear()
}
</script>

<template>
  <div class="app-container" id="app">
    <!-- 顶部banner -->
    <div class="banner-box"><img src="https://hongm-1312445828.cos.ap-nanjing.myqcloud.com/sg_top.png" alt="" /></div>
    <!-- 面包屑 -->
    <div class="breadcrumb">
      <span>🏠</span>
      /
      <span>购物车</span>
    </div>
    <!-- 购物车主体 -->
    <div class="main" v-if="fruitList.length > 0">
      <div class="table">
        <!-- 头部 -->
        <div class="thead">
          <div class="tr">
            <div class="th">选中</div>
            <div class="th th-pic">图片</div>
            <div class="th">单价</div>
            <div class="th num-th">个数</div>
            <div class="th">小计</div>
            <div class="th">操作</div>
          </div>
        </div>
        <!-- 身体 -->
        <div class="tbody">
          <div v-for="item in fruitList" :key="item.id" class="tr" :class="{ active: item.isChecked }">
            <div class="td">
              <input type="checkbox" v-model="item.isChecked" />
            </div>
            <div class="td">
              <img :src="item.icon" alt="" />
            </div>
            <div class="td">{{ item.price }}</div>
            <div class="td">
              <div class="my-input-number">
                <button :disabled="item.num <= 1" class="decrease" @click="subGoods(item.id)"> - </button>
                <span class="my-input__inner">{{ item.num }}</span>
                <button class="increase" @click="addGoods(item.id)"> + </button>
              </div>
            </div>
            <div class="td">{{ item.price * item.num }}</div>
            <div class="td">
              <button @click="delGoods(item.id)">删除</button>
            </div>
          </div>
        </div>
      </div>
      <!-- 底部 -->
      <div class="bottom">
        <!-- 全选 -->
        <label class="check-all">
          <input type="checkbox" v-model="isAll" />
          全选
        </label>
        <div class="right-box">
          <!-- 所有商品总价 -->
          <span class="price-box">总价&nbsp;&nbsp;:&nbsp;&nbsp;¥&nbsp;<span class="price">{{ totalPrice }}</span></span>
          <!-- 结算按钮 -->
          <button class="pay">结算( {{ total }} )</button>
        </div>
      </div>
    </div>
    <!-- 空车 -->
    <div class="empty" v-else>🛒空空如也</div>

    <button @click="setData">存数据</button>
    <button @click="getData">取数据</button>
    <button @click="delData">删除数据</button>
    <button @click="clearData">清空数据</button>
  </div>
</template>

<style scoped>
@import './styles/inputnumber.css';
@import './styles/index.css';
</style>